package binarytree;

import java.awt.desktop.SystemSleepEvent;
import java.io.*;
import java.util.*;

public class HuffmanCode {
    public static void main(String[] args) {
//
//        String srcFile = "D://c.png";
//        String dstFile = "D://a.zip";
//        zipFile(srcFile,dstFile);
//        System.out.println("压缩完成！");


        String zipFile = "D://a.zip";
        String dstFile = "D://a2.png";
        unZipFile(zipFile,dstFile);
        System.out.println("解压完成");

        /*String content = "hello boy jjj";
        byte[] contentBytes = content.getBytes();

        //System.out.println(" " + nodes);

        //preOrder(huffmanTree);
        byte[] huffmanCodesBytes = huffmanZip(contentBytes);


        byte[] sourceBytes = decode(huffmanCodes, huffmanCodesBytes);
        System.out.println(new String(sourceBytes));
        System.out.println(lastByteBits);*/


    }
    public static void unZipFile(String zipFile,String dstFile){
        InputStream is = null;
        ObjectInputStream ois = null;
        OutputStream os =null;
        try {
            is = new FileInputStream(zipFile);
            ois = new ObjectInputStream(is);
            byte[] huffmanBytes = (byte[])ois.readObject();
            Map<Byte,String > huffmanCodes = (Map<Byte,String> )ois.readObject();
            byte[] bytes = decode(huffmanCodes,huffmanBytes);
            os = new FileOutputStream(dstFile);
            os.write(bytes);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            try {
                os.close();
                ois.close();
                is.close();
            }catch (Exception e) {
                System.out.println(e.getMessage());
            }

        }
    }
    private static byte[] huffmanZip(byte[] bytes) {
        List<Node1> nodes = getNodes(bytes);
        Node1 huffmanTree = createHuffmanTree(nodes);
        Map<Byte, String> huffmanCodes = getCodes(huffmanTree);
        byte[] huffmanCodeBytes = zip(bytes, huffmanCodes);
        return huffmanCodeBytes;
    }
    public static void zipFile(String srcFile,String dstFile){
        FileInputStream is = null;
        OutputStream os =null;
        ObjectOutputStream oos = null;
       try {
           is = new FileInputStream(srcFile);
           byte[] b =new byte[is.available()];
           is.read(b);
           byte[] huffmanBytes = huffmanZip(b);
           os = new FileOutputStream(dstFile);
           oos = new ObjectOutputStream(os);
           oos.writeObject(huffmanBytes);
           oos.writeObject(huffmanCodes);
       }catch (Exception e){
           System.out.println(e.getMessage());
       }finally {
           try {
               is.close();
               oos.close();
               os.close();
           }catch (Exception e){
               System.out.println(e.getMessage());
           }
       }
    }


    //赫夫曼解码
    private static byte[] decode(Map<Byte, String> huffmanCodes, byte[] huffmanBytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < huffmanBytes.length; i++) {
            byte b = huffmanBytes[i];
            boolean flag = (i == huffmanBytes.length - 1);
            stringBuilder.append(byteToBitString(!flag, b));
        }
        //System.out.println(stringBuilder.toString());
        Map<String, Byte> map = new HashMap<String, Byte>();
        for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()) {
            map.put(entry.getValue(), entry.getKey());
        }
        List<Byte> list = new ArrayList<>();
        for (int i = 0; i < stringBuilder.length(); ) {
            int count = 1;
            boolean flag = true;
            Byte b = null;
            while (flag) {
                String key = stringBuilder.substring(i, i + count);
                b = map.get(key);
                if (b == null) {
                    count++;
                } else {
                    flag = false;
                }
            }
            list.add(b);
            i += count;
        }
        byte b[] = new byte[list.size()];
        for (int i = 0; i < b.length; i++) {
            b[i] = list.get(i);
        }
        return b;
    }


    public static String byteToBitString(boolean flag, byte b) {
        int temp = b;
        if (flag && b >= 0) {
            temp |= 256;
        }else {
            temp &= 0x000000ff;
        }
        String str = Integer.toBinaryString(temp);
        //System.out.println("str="+str);
        if (flag) {
            return str.substring(str.length() - 8);
        } else {
            if (str.length() == lastByteBits)
                return str;
            else {
                for (int i = 0; i < lastByteBits - str.length(); i++) {
                    str = "0" + str;
                }
                return str;
            }
        }
    }

    static byte lastByteBits = 0;

    private static byte[] zip(byte[] bytes, Map<Byte, String> huffmanCodes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : bytes) {
            stringBuilder.append(huffmanCodes.get(b));
        }
        //System.out.println(stringBuilder.toString());
        int len = (stringBuilder.length() + 7) / 8;
        byte[] huffmanCodeBytes = new byte[len];
        int index = 0;
        for (int i = 0; i < stringBuilder.length(); i += 8) {
            String strByte;
            if (i + 8 > stringBuilder.length()) {
                strByte = stringBuilder.substring(i);
                lastByteBits = (byte) strByte.length();
            } else {
                strByte = stringBuilder.substring(i, i + 8);
            }
            huffmanCodeBytes[index] = (byte) Integer.parseInt(strByte, 2);
            index++;

        }
        return huffmanCodeBytes;
    }


    static Map<Byte, String> huffmanCodes = new HashMap<Byte, String>();
    static StringBuilder stringBuilder = new StringBuilder();

    private static Map<Byte, String> getCodes(Node1 node) {
        if (node == null) {
            return null;
        }
//        getCodes(node.left, "0", stringBuilder);
//        getCodes(node.right, "1", stringBuilder);
        getCodes(node, "", stringBuilder);

        return huffmanCodes;
    }

    /**
     * @param node          传入结点
     * @param code          路径：左子结点 0 右 1
     * @param stringBuilder 拼接路径
     */
    private static void getCodes(Node1 node, String code, StringBuilder stringBuilder) {
        StringBuilder stringBuilder1 = new StringBuilder(stringBuilder);
        stringBuilder1.append(code);
        if (node != null) {
            if (node.data == null) {
                getCodes(node.left, "0", stringBuilder1);
                getCodes(node.right, "1", stringBuilder1);
            } else {
                huffmanCodes.put(node.data, stringBuilder1.toString());
            }
        }
    }


    private static void preOrder(Node1 root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("树为空，无法遍历~");
        }
    }

    private static Node1 createHuffmanTree(List<Node1> nodes) {
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            Node1 leftNode = nodes.get(0);
            Node1 rightNode = nodes.get(1);
            Node1 parent = new Node1(null, leftNode.weight + rightNode.weight);
            parent.left = leftNode;
            parent.right = rightNode;
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            nodes.add(parent);
        }
        return nodes.get(0);
    }

    private static List<Node1> getNodes(byte[] bytes) { //将字节数组中每个字符(data)及对应个数(weight)的node 放入List
        List<Node1> nodes = new ArrayList<>();
        Map<Byte, Integer> counts = new HashMap<>();
        for (byte b : bytes) {
            Integer count = counts.get(b);
            if (count == null) {
                counts.put(b, 1);
            } else {
                counts.put(b, count + 1);
            }
        }
        for (Map.Entry<Byte, Integer> entry : counts.entrySet()) {
            nodes.add(new Node1(entry.getKey(), entry.getValue()));
        }
        return nodes;
    }
}

class Node1 implements Comparable<Node1> {
    Byte data;
    int weight;
    Node1 left;
    Node1 right;

    public Node1(Byte data, int weight) {
        this.data = data;
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Node1{" +
                "data=" + data +
                ", weight=" + weight +
                '}';
    }

    @Override
    public int compareTo(Node1 o) {
        return this.weight - o.weight;
    }

    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}